<template>
  <div class="freePic">
    <el-upload
      :style="{ '--width': width, '--height': height, '--border': border }"
      :action="useOss ? ossUploadUrl : minioUploadUrl"
      :data="useOss ? dataObj : null"
      :class="{ hide: value }"
      list-type="picture-card"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList"
      accept=".jpeg,.jpg,.png"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
    >
      <slot></slot>
    </el-upload>
    <el-dialog :modal="false" :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { policy } from "@/api/oss";
import { getUid, switchHost } from "@/utils/auth";
export default {
  name: "singleUpload",
  props: {
    value: String,
    uploadType: {
      type: String,
      default: "0"
    },
    width: {
      type: String,
      default: "96px"
    },
    height: {
      type: String,
      default: "96px"
    },
    border: {
      type: String,
      default: "none"
    }
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== "") {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    fileList() {
      return [
        {
          name: this.imageName,
          url: this.imageUrl
        }
      ];
    },
    showFileList: {
      get: function() {
        return (
          this.value !== null && this.value !== "" && this.value !== undefined
        );
      },
      set: function(newValue) {}
    }
  },
  data() {
    return {
      hideUpload: false,
      limit: 1,
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        callback: ""
      },
      dialogVisible: false,
      useOss: true, //使用oss->true;使用MinIO->false
      ossUploadUrl: "",

      minioUploadUrl: `${process.env.BASE_API}/minio/upload`
    };
  },
  methods: {
    emitInput(val) {
      this.$emit("input", val);
    },
    handleRemove(file, fileList) {
      this.emitInput("");
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      console.log(file);
      let _self = this;
      if (!this.useOss) {
        //不使用oss不需要获取策略
        return true;
      }
      return new Promise((resolve, reject) => {
        policy(this.uploadType)
          .then(response => {
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
            let fileName = file.name.replace(/,/g, "-");
            _self.dataObj.key =  response.data.dir + new Date().getTime() + fileName ;
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            _self.ossUploadUrl = response.data.host;
            _self.dataObj.callback = response.data.callback;
            resolve(true);
          })
          .catch(err => {
            // console.log(err)
            reject(false);
          });
      });
    },
    handleUploadSuccess(res, file) {
      this.showFileList = true;
      this.fileList.pop();
      // if (!this.useOss) {
      //   //不使用oss直接获取图片路径
      //   url = switchHost(res.data.url);
      // }
      this.fileList.push({ name: file.name, url: res.data.filename });
      console.log(this.fileList);
      this.emitInput(this.fileList[0].url);
      this.$emit("uploadSucces");
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .el-upload--picture-card {
  background-color: #fff;
  border: var(--border);
  width: var(--width);
  height: var(--height);

  line-height: var(--height);
}
/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: var(--width);
  height: var(--height);
}

.freePic .hide /deep/ .el-upload--picture-card {
  display: none;
}
</style>
